
from starlette.requests import Request
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates

from app.api.file_handle import handle_log_file, handle_report_file, handle_log_number_file, download_file
from app.api.human_input_handle import handle_thread_identifier, initialize_new_thread, process_user_input, \
    get_thread_identifier
from app.graph import DataRequirementAnalysisWorkflow
from app.models import ChatResponse, ChatRequest, LogFileRequest, LogFileResponse, LogFileNumRequest, LogFileNumResponse
from fastapi.middleware.cors import CORSMiddleware
# 初始化FastAPI应用
import uvicorn
from fastapi import FastAPI
etl_app = FastAPI(title="数据需求分析工作流API")
etl_app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
# 配置CORS
etl_app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源，生产环境中应指定具体的前端域名
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有HTTP头
)

workflow = DataRequirementAnalysisWorkflow().build()

@etl_app.get("/")
async def read_root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})


@etl_app.get("/getid")
def get_thread_id():
     """获得每次对话的用户id"""
     thread_id = get_thread_identifier()
     return thread_id


@etl_app.post("/chat", response_model=ChatResponse)
def chat(request: ChatRequest):
    """处理聊天请求的主函数"""
    thread_id, config = handle_thread_identifier(request.thread_id,workflow)
    return process_user_input(thread_id, config, request.user_input,workflow)




@etl_app.get("/download/{filename}")
def logfile(filename: str):
    """处理聊天请求的主函数"""
    return download_file(filename)


@etl_app.post("/logfilenum", response_model=LogFileNumResponse)
def logfile(request: LogFileNumRequest):
    """处理聊天请求的主函数"""
    return handle_log_number_file(request.thread_id,request.file_number)



if __name__ == "__main__":
    uvicorn.run(etl_app, host="0.0.0.0", port=8000)